const https = require('https') // 若为http2则把'https'模块改为'spdy'模块
const fs = require('fs')
const express = require('express')

const app = express()

const options = {
  key: fs.readFileSync(`${__dirname}/server.key`),
  cert: fs.readFileSync(`${__dirname}/server.crt`)
}
// 设置响应头允许跨域
const allow = (res) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "X-Requested-With")
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS")
}

app.get('/option/?', (req, res) => {
	allow(res) // 调用允许跨域的方法
	let size = req.query['size']
	let delay = req.query['delay']
	let buf = Buffer.alloc(size * 1024 * 1024)
    //模拟服务端处理请求(如操作数据库)的时间 delay为服务端接收到前端的请求 到 向前端返回响应的时间
	setTimeout(() => {
		res.send(buf.toString('utf8'))
	}, delay)
})

https.createServer(options, app).listen(1001, (err) => { // http2服务器端口为1002
	if (err) throw new Error(err)
	console.log('Https_1.x server listening on port 1001.')
})
